package com.sdy.dcsb.web.controller.inboundservice;

import com.sdy.dcsb.web.controller.inboundservice.util.ProcessorUtil;
import com.sdy.dcsb.web.controller.inboundservice.util.ServiceUtil;
import com.sdy.dcsb.web.controller.inboundservice.util.ServletUtil;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.MimeHeaders;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * webservice类接口
 * </p>
 *
 * @author fb
 * @since 2019/11/6
 */
@Slf4j
@Controller
@RequestMapping("/DCSBWeb/services")
@Api(tags = "webservice类接口")
public class WebsServiceController extends BaseController {

    @Autowired
    private ProcessorUtil processorUtil;

    /**
     * 获取请求的接口编码和版本
     * @param code ,编码和版本
     * @return
     */
    @RequestMapping("/{code}")
    @ResponseBody
    @ApiOperation("获取请求的接口编码和版本")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "code", value = "编码和版本"),
    })
    public String getCode(HttpServletRequest request, @PathVariable("code") String code) throws IOException {;
        long requestTime = System.currentTimeMillis();
        String responseMsg = null;
        String servcode = null;
        String servversion = null;
        String requestIp = null;
        String requestHttpType = null;
        String queryString = null;
        MimeHeaders headers = null;
        HashMap<String, String> map = new HashMap<String, String>();
        String serviceUrl = request.getRequestURL().toString();
        String address = serviceUrl.substring(serviceUrl.indexOf("/")+2);
        String[] array = address.split("/");
        // 获取请求url中的ip+端口
        String ipAndPort = array[0];
        if(!isEmpty(code)) {
            Map<String, String> servcodeMap = ServiceUtil.getServcode(code);
            servcode = servcodeMap.get("servcode");
            servversion = servcodeMap.get("servversion");
            requestIp = ServletUtil.getIpAddr(request);
            queryString = request.getQueryString();
            Map<String, String> queryStringMap = ServiceUtil.getQueryString(queryString, responseMsg);
            if(queryStringMap.containsKey("code")) {
                return queryStringMap.get("responseMsg");
            }else {
                queryString = queryStringMap.get("queryString");
            }
            map = ServletUtil.headerMap(request);
            headers = ServletUtil.getHeaders(request);
            String[] reqLengths = headers.getHeader("Content-Length");
            long reqLength = 0;
            if(null != reqLengths && reqLengths.length > 0) {
                reqLength = Integer.parseInt(reqLengths[0]);
            }
            // 获取请求的字符集
            String reqCharset = null;
            String contentType = null;
            contentType = request.getContentType();
            Map<String, String> contentTypeMap = ServiceUtil.getContentType(contentType, request);
            contentType = contentTypeMap.get("contentType");
            reqCharset = contentTypeMap.get("reqCharset");
            String requestMsg = "";
            // 读取请求信息
            // 将请求包按流的形式解析出来
            try {
                requestMsg = inputStreamToString(request, reqCharset);
            }catch (Throwable e) {
                responseMsg = e.getMessage();
                return responseMsg;
            }
            // 把头信息放到queryString里
            if(queryString == null) {
                queryString = contentType;
            }
            if(reqLength == 0) {
                reqLength = requestMsg.length();
            }
            if(!queryString.equals(contentType)){
                reqLength = queryString.length();
            }
            // 访问标准服务
            responseMsg = processorUtil.doProcess(servcode, servversion, requestIp, requestHttpType, Integer.valueOf(String.valueOf(reqLength)),
                    queryString, contentType, requestMsg, reqCharset, requestTime, "1", ipAndPort, map, null);
            return responseMsg;
        }else {
            responseMsg = "Error url, please check !";
            return responseMsg;
        }
    }

    private String inputStreamToString(HttpServletRequest request, String encoding) throws Exception {
        if(isEmpty(request.getContentType())) {
            return "";
        }
        if(request.getContentType().contains("multipart/form-data")) {
            return ServletUtil.getReqFormBodyString(request, encoding);
        }else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), encoding));
            StringBuffer sb = new StringBuffer();
            String line = null;
            String requestMsg = null;
            try {
                while((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }catch (IOException e) {
                throw e;
            }finally {
                try {
                    request.getInputStream().close();
                }catch (IOException e) {
                    throw e;
                }
            }
            requestMsg = sb.toString();
            requestMsg = StringEscapeUtils.unescapeHtml4(requestMsg);
            return requestMsg;
        }
    }

}
